﻿/*
 * ========================================================================
 * Copyright(c) 2008-2010北京高阳金信信息技术有限公司, All Rights Reserved.
 * ========================================================================
 * 通用公共方法--基于数据库的配置信息操作类
 *  drop table  if exists  tb_sys_config;
 * create table TB_Sys_Config
 *  (
 *   [ID] [integer] primary key not null,
 *   [Key]  varchar(50) not null,--键
 *   [Value]  varchar(100),   --值
 *   [ExtValue]  varchar(1000), --扩展属性值，备用
 *   [AtDateTime] datetime --记录创建或者修改的时间
 *  );
 *  
 *  Key 可以有重复值，默认取第一个。
 *  ExtValue 可以存放较大容量的其它备注信息
 * 
 * 作者：邓太华     时间：2009-12-15
 * 版本：Ver 3.370
 * 
 * 修改者：邓太华         时间：2009-12-9                
 * 修改说明：
 * ========================================================================
*/


using System;
using System.Collections.Generic;
using System.Text;
using PWMIS.DataProvider.Adapter;

namespace Hisuntech.SystemFramework.Common
{
    /// <summary>
    /// 基于数据库的配置信息操作类
    /// </summary>
    public class ConfigInDb
    {
        private static ConfigInDb _Instance=null;

        private ConfigInfo[] configs = null;
        private static object lockObj = new object();

        /// <summary>
        /// 默认构造函数
        /// </summary>
        public ConfigInDb()
        {
            configs = ReadAllConfig();
        }

        /// <summary>
        /// 获取唯一实例
        /// </summary>
        public static ConfigInDb Instance
        {
            get
            {
                
                if (_Instance == null)
                {
                    lock (lockObj)
                    {
                        if(_Instance == null)
                            _Instance = new ConfigInDb();
                    
                    }
                }
                
                if (_Instance.configs == null)
                {
                    _Instance.configs = _Instance.ReadAllConfig();
                }
                return _Instance;
            }
        }


        /// <summary>
        /// 根据键获取值，键不区分大小写
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string ReadKey(string key)
        {
            ConfigInfo info = ReadConfig(key);
            if (info != null)
                return info.Value;
            return "";
        }

        /// <summary>
        /// 根据键获取配置记录信息，键不区分大小写
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public ConfigInfo ReadConfig(string key)
        {
            if (configs != null)
            {
                foreach (ConfigInfo info in configs)
                {
                    if (String.Compare ( info.Key,key,true )==0)
                        return info;
                }
            }
            return null;
        }

        /// <summary>
        /// 根据标示取配置记录信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ConfigInfo ReadConfig(int id)
        {
            if (configs != null)
            {
                foreach (ConfigInfo info in configs)
                {
                    if (info.Id == id)
                        return info;
                }
            }
            return null;
        }

        private ConfigInfo[] ReadAllConfig()
        {
            string sql = "select * from TB_Sys_Config order by id";
            
            try
            {
                System.Data.DataSet ds = MyDB.Instance.ExecuteDataSet(sql);
                if (ds.Tables.Count > 0)
                {
                    System.Data.DataTable dt = ds.Tables[0];
                    if (dt.Rows.Count > 0)
                    {
                        ConfigInfo[] infos = new ConfigInfo[dt.Rows.Count];
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            System.Data.DataRow dr = dt.Rows[i];
                            infos[i] = new ConfigInfo();
                            infos[i].Id = Convert.ToInt32(dr["ID"].ToString());
                            infos[i].Key = dr["Key"].ToString();
                            infos[i].Value = dr["Value"].ToString();
                            infos[i].ExtValue = dr["ExtValue"].ToString();
                            infos[i].AtDateTime = dr["AtDateTime"] == DBNull.Value ? DateTime.Now : Convert.ToDateTime(dr["AtDateTime"].ToString());
                        }
                        return infos;
                    }
                }
                else
                {
                    throw new System.Exception("配置信息表 不存在。");
                }
                
            }
            catch (System.Exception ex)
            {
                //可能表不存在,创建表
                string ddl = @"
                create table TB_Sys_Config
(
  [ID] [integer] primary key not null,
  [Key]  varchar(50) not null,
  [Value]  varchar(100),  
  [ExtValue]  varchar(1000), 
  [AtDateTime] datetime 
);
                ";
                System.Diagnostics.Debug.WriteLine(ex.Message);
                MyDB.Instance.ExecuteNonQuery (ddl);

            }
            return null;


        }

        /// <summary>
        /// 根据键获取多个配置信息
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public IEnumerable<ConfigInfo> ReadKeys(string key)
        {
            if (configs != null)
            {
                foreach (ConfigInfo info in configs)
                {
                    if (String.Compare(info.Key, key, true) == 0)
                        yield return info;
                }
            }

            //return null;
        }

        private bool SaveToDb(int id, string key, string Value, string extValue, bool insert)
        {
            if (extValue == null)
                extValue = "";

            string sql = "";
            if (insert)
                sql = "insert into TB_Sys_Config([ID],[Key],[Value],[ExtValue],[AtDateTime]) values(@ID,@Key,@Value,@ExtValue,@AtDateTime)";
            else
                sql = "update TB_Sys_Config Set [Key]=@Key,[Value]=@Value,[ExtValue]=@ExtValue,[AtDateTime]=@AtDateTime where ID=@ID";
            
            System.Data.IDataParameter[] paras ={
                                                        MyDB.Instance.GetParameter ( "@ID",id ),
                                                        MyDB.Instance.GetParameter ("@Key",key ),
                                                        MyDB.Instance.GetParameter("@Value",Value ),
                                                        MyDB.Instance.GetParameter ("@ExtValue",extValue),
                                                        MyDB.Instance.GetParameter("@AtDateTime",DateTime .Now )
                                                        };
            int count = MyDB.Instance.ExecuteNonQuery(sql, System.Data.CommandType.Text, paras);
            
            return count > 0;
        }

        /// <summary>
        /// 写入配置信息
        /// </summary>
        /// <param name="key"></param>
        /// <param name="Value"></param>
        /// <param name="extValue"></param>
        /// <returns></returns>
        public bool WriteKey(string key, string Value, string extValue)
        {
            if (configs != null)
            {
                ConfigInfo info = this.ReadConfig(key);
                //扩展熟悉不指定，则使用原来的值
                if (extValue == null && info != null)
                    extValue = info.ExtValue;

                int ID = configs[configs.Length - 1].Id + 1;

                bool insert = false;
                if (info == null)//如果该键不存在，则插入记录
                    insert = true;
                else
                    ID = info.Id;

                if (SaveToDb(ID, key, Value, extValue, insert))
                {
                    configs = ReadAllConfig ();//清除缓存
                    return true;
                }
            }
            else
            {
                //插入第一条记录
                return SaveToDb(1, key, Value, extValue, true);
            }
            return false;
        }

        /// <summary>
        /// 写入配置信息
        /// </summary>
        /// <param name="key"></param>
        /// <param name="Value"></param>
        /// <returns></returns>
        public bool WriteKey(string key, string Value)
        {
            return WriteKey(key, Value, null);
        }

        /// <summary>
        /// 写入配置信息
        /// </summary>
        /// <param name="key"></param>
        /// <param name="Value"></param>
        /// <returns></returns>
        public bool SaveKey(string key, string Value)
        {
            return WriteKey(key, Value, null);
        }

        /// <summary>
        /// 写入配置信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public bool WriteConfig(ConfigInfo info)
        {
            return WriteKey(info.Key, info.Value, info.ExtValue);
        }

        /// <summary>
        /// 根据一个键，写入多个配置信息。注意只写入跟键匹配的配置信息，其它忽略。（改方法暂时未实现）
        /// </summary>
        /// <param name="key"></param>
        /// <param name="infos"></param>
        /// <returns></returns>
        public bool WriteConfig(string key, ConfigInfo[] infos)
        {
            return false;
        }

        /// <summary>
        /// 配置信息
        /// </summary>
        public class ConfigInfo
        {
            public ConfigInfo() { }

            public ConfigInfo(int id, string key, string Value, string extValue)
            {
                this.Id = id;
                this.Key = key;
                this.ExtValue = extValue;
                this.AtDateTime = DateTime.Now;
            }

            int _id;

            /// <summary>
            /// 标示
            /// </summary>
            public int Id
            {
                get { return _id; }
                set { _id = value; }
            }
            string _key;

            /// <summary>
            /// 键
            /// </summary>
            public string Key
            {
                get { return _key; }
                set { _key = value; }
            }
            string _value;

            /// <summary>
            /// 值
            /// </summary>
            public string Value
            {
                get { return _value; }
                set { _value = value; }
            }
            string _extValue;

            /// <summary>
            /// 扩展属性
            /// </summary>
            public string ExtValue
            {
                get { return _extValue; }
                set { _extValue = value; }
            }
            DateTime _atDateTime;

            /// <summary>
            /// 发生时间
            /// </summary>
            public DateTime AtDateTime
            {
                get { return _atDateTime; }
                set { _atDateTime = value; }
            }


        }
    }
}
